package cn.yangliu.nacos.comm.config.security.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yangliu.nacos.comm.JsonResult;
import cn.yangliu.nacos.comm.ex.ResultCode;
import cn.yangliu.nacos.comm.tools.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

/**
 * The interface Security handler.
 *
 * @author 问道于盲
 */
public interface SecurityHandler {

    /**
     * 默认的认证异常
     *
     * @param request    请求
     * @param response   响应
     * @param ex         异常
     * @param httpStatus 响应状态
     * @param resultCode 响应信息
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    default void handle(HttpServletRequest request, HttpServletResponse response, Exception ex,
                        HttpStatus httpStatus, ResultCode resultCode) throws IOException, ServletException {
       handle(request, response, httpStatus, resultCode, null, null);
    }

    /**
     * 默认的认证异常
     *
     * @param request    请求
     * @param response   响应
     * @param httpStatus 响应状态
     * @param resultCode 响应信息
     * @param message    响应信息
     * @param data       the data
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    default void handle(HttpServletRequest request, HttpServletResponse response,
                        HttpStatus httpStatus, ResultCode resultCode, String message, Object data) throws IOException, ServletException {
//        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(httpStatus.value());
        PrintWriter out = response.getWriter();
        JsonResult<Object> result = JsonResult.getInstance(resultCode);
        if (!StringUtils.isEmpty(message)){
            result.setMsg(message);
        }
        result.setData(data);
        out.write(JsonUtils.objectToJson(result));
        out.flush();
        out.close();
    }


    /**
     * 默认的认证异常
     *
     * @param request    请求
     * @param response   响应
     * @param httpStatus 响应状态
     * @param resultCode 响应信息
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    default void handle(HttpServletRequest request, HttpServletResponse response,
                        HttpStatus httpStatus, ResultCode resultCode) throws IOException, ServletException {
        handle(request, response, null, httpStatus, resultCode);
    }
}
